﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Diploma.Models;
using DiplomaWeb.Models;
using DiplomaWeb.Models.OrderPractice;
using DiplomaWeb.Models.Student;
using MvcPaging;

namespace DiplomaWeb.Controllers
{
    [Authorize(Roles = "SystemManager")]
    public class OrderPracticeController : MasterController
    {
        private int PageSize = 20;

        public OrderPracticeController(DataManager dataManager)
            : base(dataManager)
        {
        }

        #region Management OrderPractice

        public ActionResult Home(int? page, int? pageSize)
        {
            var viewModel = new OrderPracticeViewModel
                                {
                                    Orders =
                                        DataManager.OrderPracticeRepository.GetAll().ToArray().ToPagedList(
                                            page.HasValue ? page.Value : 1,
                                            pageSize.HasValue
                                                ? pageSize.Value
                                                : PageSize),
                                    Search = new SearchOrderPracticeModel()
                                };

            return View("~/Views/SystemManagers/OrderPractice/Orders.aspx", viewModel);
        }

        public ActionResult New()
        {
            var model = new OrderPractice
                            {
                                Id = Guid.NewGuid(),
                                Name = "Новый приказ на практику",
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                IsVerify = false,
                                Students = null,
                                SaveStateOrderPractices = null
                            };
            this.DataManager.OrderPracticeRepository.CreateOrder(model);
            return RedirectToRoute("Default", new
                                                  {
                                                      controller = "OrderPractice",
                                                      action = "Room",
                                                      orderId = model.Id
                                                  });
        }

        /// <summary>
        /// Работа с приказом
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Room(Guid orderId)
        {
            OrderPractice model = DataManager.OrderPracticeRepository.GetOrder(orderId);
            ViewData.Model = model;
            return View("~/Views/SystemManagers/OrderPractice/OrderRoom.aspx");
        }

        public ActionResult DeleteOrderPractice(Guid orderId)
        {
            DataManager.OrderPracticeRepository.Delete(orderId);
            return RedirectToRoute("Default", new
                                                  {
                                                      controller = "OrderPractice",
                                                      action = "Home",
                                                  });
        }

        #endregion

        #region Ajax Management OrderPractice

        [HttpPost]
        public JsonResult GetOrders(int? nd, bool _search, string sidx, string sord, int page, int rows)
        {
            IEnumerable<OrderPractice> list = DataManager.OrderPracticeRepository.GetAll();

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = list.Count();
            var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);

            var orders = list.OrderBy(r => sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).Select(r =>
                                                                                                             new
                                                                                                                 {
                                                                                                                     Id
                                                                                                                 =
                                                                                                                 "<a href='" +
                                                                                                                 Url.
                                                                                                                     RouteUrl
                                                                                                                     ("Default",
                                                                                                                      new
                                                                                                                          {
                                                                                                                              controller
                                                                                                                          =
                                                                                                                          "OrderPractice",
                                                                                                                              action
                                                                                                                          =
                                                                                                                          "Room",
                                                                                                                              orderId
                                                                                                                          =
                                                                                                                          r
                                                                                                                          .
                                                                                                                          Id
                                                                                                                          }) +
                                                                                                                 "'>" +
                                                                                                                 "More" +
                                                                                                                 "</a>",
                                                                                                                     r.
                                                                                                                 Name,
                                                                                                                     CreateDate
                                                                                                                 =
                                                                                                                 String.
                                                                                                                 Format(
                                                                                                                     "{0:d}",
                                                                                                                     r.
                                                                                                                         CreateDate),
                                                                                                                     UpdateDate
                                                                                                                 =
                                                                                                                 String.
                                                                                                                 Format(
                                                                                                                     "{0:d}",
                                                                                                                     r.
                                                                                                                         UpdateDate),
                                                                                                                     IsVerify
                                                                                                                 =
                                                                                                                 r.
                                                                                                                 IsVerify
                                                                                                                 .
                                                                                                                 ToString
                                                                                                                 ()
                                                                                                                 });


            var result = new JsonResult
                             {
                                 Data = new { page, total = totalPages, records = orders.Count(), rows = orders }
                             };

            return result;
        }

        /// <summary>
        /// Отображение уровней специальности
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAllLevels()
        {
            List<QualificationLevel> model = DataManager.QualificationLevelsRepository.GetAllLevels();

            ViewData["AllLevels"] = from b in model
                                    select new SelectListItem
                                               {
                                                   Text = b.Name,
                                                   Value = b.QualificationLevelId.ToString()
                                               };

            return PartialView("~/Views/SystemManagers/Orders/AllLevels.ascx");
        }

        /// <summary>
        /// Отображение всех групп
        /// </summary>
        /// <param name="levelId">Группа</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetGroups(int levelId)
        {
            IEnumerable<StudentsGroup> groups = from b in DataManager.StudentsGroupsRepository.GetAllGroups()
                                                where b.QualificationLevelId == levelId
                                                select b;

            ViewData["AllGroups"] = from b in groups
                                    select new SelectListItem
                                               {
                                                   Text = b.Name,
                                                   Value = b.StudentsGroupId.ToString()
                                               };

            return PartialView("~/Views/SystemManagers/Orders/AllGroups.ascx");
        }

        /// <summary>
        /// Добавление группы к приказу
        /// </summary>
        /// <param name="groupId">Группа</param>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AttachStudentToOrder(Guid groupId, Guid orderId)
        {
            try
            {
                DataManager.OrderPracticeRepository.AttachStudentsToOrder(groupId, orderId);

                return Json(new { response = true });
            }
            catch
            {
                return Json(new { response = false });
            }
        }

        /// <summary>
        /// Редактировани информации о приказе
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <param name="orderName">Новое имя приказа</param>
        /// <param name="startDate">Начало практики</param>
        /// <param name="endDate">Окончание практики</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveEditInfo(Guid orderId, string orderName, string startDate, string endDate)
        {
            OrderPractice model = DataManager.OrderPracticeRepository.GetOrder(orderId);
            model.Name = orderName;
            DataManager.OrderPracticeRepository.SaveChanges();
            return Json(new { status = true });
        }


        /// <summary>
        /// Загрузка информации о приказе
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult LoadInfo(Guid orderId)
        {
            ViewData.Model = DataManager.OrderPracticeRepository.GetOrder(orderId);

            return PartialView("~/Views/SystemManagers/OrderPractice/OrderInfo.ascx");
        }

        /// <summary>
        /// Загрузка формы редактирования информации приказа
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult LoadEditInfo(Guid orderId)
        {
            ViewData.Model = DataManager.OrderPracticeRepository.GetOrder(orderId);

            return PartialView("~/Views/SystemManagers/OrderPractice/EditOrderInfo.ascx");
        }

        [HttpPost]
        public ActionResult RefreshStudentList(Guid orderId)
        {
            OrderPractice model = DataManager.OrderPracticeRepository.GetOrder(orderId);

            var viewModel = new StudentListPracticeViewModel();
            viewModel.ToViewModel(model);

            if (model.IsVerify.HasValue && model.IsVerify.Value)
            {
                viewModel.Students = viewModel.Students.OrderBy(r => r.Num).ToList();
                return PartialView("~/Views/SystemManagers/OrderPractice/SaveStateStudentList.cshtml", viewModel);
            }
            return PartialView("~/Views/SystemManagers/OrderPractice/StudentList.cshtml", viewModel);
        }

        /// <summary>
        /// Удаление пользовалетя с приказа
        /// </summary>
        /// <param name="studentId">Студент</param>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RemoveUser(Guid studentId, Guid orderId)
        {
            try
            {
                DataManager.OrderPracticeRepository.RemoveStudentsFromOrder(studentId, orderId);

                DataManager.OrderPracticeRepository.SaveChanges();

                return Json(new { response = true });
            }
            catch
            {
                return Json(new { response = false });
            }
        }

        /// <summary>
        /// Сохранение состояния приказа
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveState(Guid orderId)
        {
            OrderPractice model = DataManager.OrderPracticeRepository.GetOrder(orderId);
            var viewModel = new StudentListPracticeViewModel();
            viewModel.ToViewModel(model);

            DataManager.OrderPracticeRepository.SaveState(orderId, viewModel.Students.Select(r => r.ToEntity()));
            return RedirectToRoute("Default", new
                                                  {
                                                      controller = "OrderPractice",
                                                      action = "Room",
                                                      orderId
                                                  });
        }

        /// <summary>
        /// Отображение всех под приказов
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetSubOrders(Guid orderId)
        {
            OrderPractice order = DataManager.OrderPracticeRepository.GetOrder(orderId);

            return PartialView("~/Views/SystemManagers/OrderPractice/SubOrderPractice.ascx", order.SubOrderPractices);
        }

        /// <summary>
        /// Получение студентов которые есть уже в приказах
        /// </summary>
        /// <param name="orderId">Приказ</param>
        /// <returns>Студенты</returns>
        [HttpPost]
        public JsonResult GetStudentListInSubOrders(Guid orderId)
        {
            OrderPractice order = DataManager.OrderPracticeRepository.GetOrder(orderId);
            List<String> array = (from b in order.SaveStateOrderPractices
                                  where b.SubOrderPractices.Count != 0
                                  select b.StudentId.ToString()).ToList();
            return Json(array);
        }

        #endregion

        
    }
}